class InvitationsController < WebappController
  
  before_filter :ensure_authenticated
  #ensure_authenticated_to_facebook
  
  #Open the invitation dialog
  def new
    @from_user_id = facebook_session.user.to_s
  end
  
  def create
    sent_to_ids = params[:ids]
    sent_to_emails = params[:emails]
    @points = 0
    
    @user_invitation_with_points = Array.new
    @user_invitation_with_no_points = Array.new
    @email_invitation_with_points = Array.new
    @email_invitation_with_no_points = Array.new
    
    
    if sent_to_ids 
      for id in sent_to_ids
        ui = UserInvitation.find(:first, :conditions=>["user_id=:user_id and invited_user_fb_uid=:invited_user_fb_uid", {:user_id=>@current_user.id,:invited_user_fb_uid=>id}])
        unless ui
          #ui = UserInvitation.new
          #ui.user_id = @current_user.id
          #ui.invited_user_fb_uid = id
          #ui.save!
          @user_invitation_with_points << create_user_invitation(@current_user.id,id,nil)
        else
          @user_invitation_with_no_points << ui
        end
      end
      
      @points += @user_invitation_with_points.size*@current_user.active_campaign.points_invite_friends
    end
    
    if sent_to_emails
      for email in sent_to_emails
        ui = UserInvitation.find(:first, :conditions=>["user_id=:user_id and invited_user_email=:invited_user_email", {:user_id=>@current_user.id,:invited_user_email=>email}])
        unless ui
          #ui = UserInvitation.new
          #ui.user_id = @current_user.id
          #ui.invited_user_email = email
          #ui.save!
          @email_invitation_with_points << create_user_invitation(@current_user.id,nil,email)
        else
          @email_invitation_with_no_points << ui
        end
      end
      @points += @email_invitation_with_points.size*@current_user.active_campaign.points_invite_friends
    end
  end
  
  private 
  def create_user_invitation(user_id, invited_user_id, invited_user_email)
    ui = UserInvitation.new
    ui.user_id = user_id
    ui.invited_user_email = invited_user_email
    ui.invited_user_fb_uid = invited_user_id
    ui.save!
    ui
  end
end
